<template>
  <NvCrud v-model:form="form" :option :data @row-update="handleSave" />
</template>

<script setup lang="ts">
import type { NvCrudOption, NvOption } from 'nv-crud'
import { NvCrud } from 'nv-crud'
import { computed, ref } from 'vue'

interface Data { id?: number, name?: string, province?: string, city?: string }

const form = ref<Data>({})

const data = ref<Data[]>([
  { id: 1, name: '张三', province: 'sichuan', city: 'chengdu' },
  { id: 2, name: '李四', province: 'guangxi', city: 'nanning' },
])

function handleSave(done: (close: boolean) => void) {
  setTimeout(() => {
    const idx = data.value.findIndex(item => item.id === form.value.id)
    if (idx > -1) {
      data.value[idx] = form.value
    }
    done(true)
  }, 1000)
}

const cities: Record<string, NvOption[]> = {
  sichuan: [
    { label: '成都', value: 'chengdu' },
    { label: '绵阳', value: 'mianyang' },
  ],
  guangxi: [
    { label: '南宁', value: 'nanning' },
    { label: '柳州', value: 'liuzhou' },
  ],
}

const option: NvCrudOption<Data> = {
  actionbar: false,
  toolbar: false,
  fields: {
    name: {
      title: '姓名',
    },
    province: {
      title: '省份',
      type: 'select',
      dict: [
        { label: '四川', value: 'sichuan' },
        { label: '广西', value: 'guangxi' },
      ],
    },
    city: {
      title: '城市',
      type: 'select',
      dict: computed(() => {
        return cities[form.value.province!] || []
      }),
      cellDict: [...cities.sichuan, ...cities.guangxi],
    },
  },
}
</script>
